package com.code2roc.fastboot.framework.file;

import com.code2roc.fastboot.framework.config.SystemConfig;
import com.code2roc.fastboot.framework.util.BeanUtil;
import com.code2roc.fastboot.framework.util.CommonUtil;
import com.code2roc.fastboot.framework.util.ConvertOp;
import com.code2roc.fastboot.framework.util.FileUtil;

import java.io.*;


public class LocalFileOperate implements IFileOperate {
    private LocalFileStoargeProperty property;

    public LocalFileOperate(LocalFileStoargeProperty property) {
        this.property = property;
        String floderName = property.getLocalFilePath();
        FileUtil.initfloderPath(floderName);
    }

    @Override
    public void storageFile(String bucketName, String key, byte[] bytes) throws Exception {
        String filePath = property.getLocalFilePath() + bucketName;
        FileUtil.initfloderPath(filePath);
        filePath = filePath + "/" + key;
        File targetFile = new File(filePath);
        if (!targetFile.exists()) {
            targetFile.createNewFile();
        }
        FileUtil.writeFile(filePath, bytes);
    }

    @Override
    public void storageFile(String bucketName, String key, InputStream inputStream) throws Exception {
        storageFile(bucketName, key, ConvertOp.convertStreamToByte(inputStream));
    }

    @Override
    public void storageFileByChunk(String bucketName, String key, InputStream inputStream, String fileMD5, int chunkCount, int chunkIndex, int chunkSize) throws Exception {
        SystemConfig systemConfig = BeanUtil.getBean(SystemConfig.class);

        //检查分片
        boolean existChunk = false;
        String chunkFileFolderPath = systemConfig.getTemplatePath() + "attachchunfiles/" + fileMD5 + "/";
        FileUtil.initfloderPath(chunkFileFolderPath);
        String chunkKey = fileMD5 + "-" + chunkIndex + ".temp";
        String chunkFilePath = chunkFileFolderPath + chunkKey;
        File chunkFile = new File(chunkFilePath);
        if (chunkFile.exists()) {
            existChunk = true;
        }

        //保存分片
        if (!existChunk) {
            File targetFile = new File(chunkFilePath);
            if (!targetFile.exists()) {
                targetFile.createNewFile();
            }
            FileUtil.writeFile(chunkFilePath, ConvertOp.convertStreamToByte(inputStream));
        }

        //合并分片
        if (chunkIndex == chunkCount - 1) {
            String merageFilePath = chunkFileFolderPath + fileMD5 + ".temp";
            File merageFile = new File(merageFilePath);
            if (!merageFile.exists()) {
                BufferedOutputStream destOutputStream = new BufferedOutputStream(new FileOutputStream(merageFilePath));
                for (int i = 0; i < chunkCount; i++) {
                    File file = new File(chunkFileFolderPath + fileMD5 + "-" + i + ".temp");
                    byte[] fileBuffer = new byte[1024 * 1024 * 5];//文件读写缓存
                    int readBytesLength = 0; //每次读取字节数
                    BufferedInputStream sourceInputStream = new BufferedInputStream(new FileInputStream(file));
                    while ((readBytesLength = sourceInputStream.read(fileBuffer)) != -1) {
                        destOutputStream.write(fileBuffer, 0, readBytesLength);
                    }
                    sourceInputStream.close();
                }
                destOutputStream.flush();
                destOutputStream.close();
            }
            String targetFilePath = property.getLocalFilePath() + bucketName;
            FileUtil.initfloderPath(targetFilePath);
            targetFilePath = targetFilePath + "/" + key;
            FileUtil.copyFile(merageFilePath, targetFilePath);
        }

    }

    @Override
    public byte[] getFileBytes(String bucketName, String key) throws Exception {
        String filePath = property.getLocalFilePath() + bucketName + "/" + key;
        return FileUtil.getBytes(filePath);
    }

    @Override
    public void copyFile(String originBucketName, String originFileKey, String newBucketName, String newFileKey) throws Exception {
        String filePath = property.getLocalFilePath() + originBucketName + "/" + originFileKey;
        String newFilePath = property.getLocalFilePath() + newBucketName;
        FileUtil.initfloderPath(newFilePath);
        newFilePath = newFilePath + "/" + newFileKey;
        FileUtil.copyFile(filePath, newFilePath);
    }

    @Override
    public String getFileUrl(String bucketName, String key) throws Exception {
        return CommonUtil.getRootPath() + bucketName + "/" + key;
    }

    @Override
    public void deleteFile(String bucketName, String key) throws Exception {
        String filePath = property.getLocalFilePath() + bucketName + "/" + key;
        FileUtil.deleteFile(filePath);
        String dirPath = property.getLocalFilePath() + bucketName;
        File dir = new File(dirPath);
        if (dir.listFiles().length == 0) {
            FileUtil.deleteFileFolder(dirPath);
        }
    }

    @Override
    public String getFileSize(String bucketName, String key) throws Exception {
        String filePath = property.getLocalFilePath() + bucketName + "/" + key;
        File file = new File(filePath);
        if (file.exists()) {
            return ConvertOp.convert2String(file.length());
        } else {
            return "0";
        }
    }

    @Override
    public FileStoargeProperty getFileStoargeProperty() {
        return property;
    }
}
